<template>
  <div class="personnel-container flex-column">
    <div class="flex-row justify-between">
      <div class="flex-row">
        <custom-button class="custom-button" @click="addUser"></custom-button>
        <!-- <custom-button class="custom-button" title="删除" ></custom-button>-->
      </div>
      <el-input
        v-model="queryInfo.userName"
        class="input-width"
        placeholder="请输入用户名"
        @input="handleUserSearch"
      >
        <div slot="suffix" class="el-icon-search search-button" @click="handleUserSearch"></div>
      </el-input>
    </div>
    <!-- 用户列表 -->
    <div class="flex-sub table-container">
      <el-table
        v-loading="showList"
        :data="tableData"
        height="98%"
        header-cell-class-name="table-header-cell"
        header-row-class-name="table-header-row"
      >
        <!-- <el-table-column type="selection" :width="handleScreenWidthToVw(55)+'px'" /> -->
        <el-table-column prop="account" label="用户帐号" />
        <el-table-column prop="userOrgs[0].name" label="所属组织" />
        <el-table-column prop="date" label="关联人员" />
        <el-table-column prop="dataStatusName" label="状态" />
        <el-table-column label="创建时间">
          <template slot-scope="scope">
            <span>{{ scope.row.createTime | dateFormat }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          fixed="right"
          :width="handleScreenWidthToVw(150)+'px'"
          align="center"
        >
          <div slot-scope="scope">
            <span size="small" class="btn-edit" @click="updateUser(scope.row)">修改</span>
            <span class="lh-23">|</span>
            <span class="btn-delete " @click="delUser(scope.row.id)">删除</span>
          </div>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <el-pagination
      hide-on-single-page
      background
      layout="prev, pager, next, total, jumper"
      :current-page="page.pageNo"
      :page-size="page.pageSize"
      :total="page.total"
      @current-change="handleCurrentChange"
    />
    <!-- 用户弹窗 -->
    <el-dialog
      :title="title"
      :before-close="cancel"
      :visible.sync="dialogVisible.addUser"
      :width="handleScreenWidthToVw(574)+'px'"
      :close-on-click-modal="false"
    >
      <el-form
        ref="userForm"
        :model="form"
        class="demo-form-inline"
        :rules="Rules"
        :label-width="handleScreenWidthToVw(120)+'px'"
        style="text-align: left;"
      >
        <el-form-item v-if="!selChange" label="用户帐号：" prop="account">
          <el-input v-model="form.account" placeholder="请输入用户帐号" class="form-input-width" />
        </el-form-item>
        <el-form-item v-else label="用户帐号：">
          <div style="text-align: left;">
            {{ form.account }}
          </div>
        </el-form-item>
        <el-form-item label="设置新密码" prop="password">
          <el-input type="password" v-model="form.password" placeholder="请输入新密码"></el-input>
        </el-form-item>
        <el-form-item label="所属组织：" prop="seleteOrg">
          <el-select
            ref="orgSelect"
            v-model="form.seleteOrg"
            placeholder="请选择"
            class="form-input-width"
          >
            <el-option value="form.seleteOrg" class="selete-org-bg">
              <el-tree
                ref="tree"
                :data="depData"
                :props="defaultProps"
                :highlight-current="true"
                @node-click="handleNodeClick"
              />
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属角色：">
          <el-select v-model="roleForm" placeholder="请选择" class="form-input-width" multiple>
            <el-option
              v-for="(item, index) in roleData"
              :key="index"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="用户状态：" prop="state">
          <el-radio v-model="form.dataStatusEnum" label="NORMAL">正常</el-radio>
          <el-radio v-model="form.dataStatusEnum" label="STOP">停用</el-radio>
        </el-form-item>
        <el-form-item label="用户说明：" prop="explainText">
          <el-input v-model="form.explainText" placeholder="请输入用户说明"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <SubButton v-if="!selChange" @subClick="subUserFrom" />
        <SubButton v-else @subClick="updateUserFrom" />
        <CancelButton @cancelClick="cancel" />
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getUserlist,
  findOrgList,
  addUserlist,
  delUserList,
  updateUserlist,
  findUserPageByParam,
  findRoleList,
} from './api'
import { tree } from '@/utils/tree'
import dayjs from 'dayjs'
import SubButton from '@/components/sub-button/index.vue'
import CancelButton from '@/components/cancel-button/index.vue'
import { handleScreenWidthToVw } from '@/utils/tools'

export default {
  components: { SubButton, CancelButton },
  filters: {
    dateFormat(value) {
      return dayjs(value).format('YYYY-MM-DD HH:mm:ss')
    },
  },

  data() {
    return {
      title: '',
      selChange: null,
      queryInfo: {
        userName: '',
        phone: '',
      },
      dialogVisible: { addUser: false, innerRole: false },
      filterText: '',
      form: {
        account: '',
        password: '',
        seleteOrg: '',
        dataStatusEnum: 'NORMAL',
        userOrgs: [],
        orgUserVo: null,
        userRoles: [],
        explainText:''
      },
      depData: [],
      roleData: [],
      roleForm: [],
      tableData: [],
      page: {
        pageNo: 1,
        pageSize: 14,
        total: null,
      },
      showList: true,
    }
  },
  computed: {
    defaultProps() {
      return {
        children: 'children',
        label: 'name',
      }
    },
    handleScreenWidthToVw() {
      return handleScreenWidthToVw
    },
    Rules() {
      return {
        account: [
          { required: true, message: '请输入用户帐号', trigger: ['blur', 'change'] },
          // { min: 1, max: 10, message: "长度不超过 10 个字符", trigger: "blur" },
        ],
        dataStatusEnum: [{ required: true, message: '请选择状态', trigger: 'change' }],
        seleteOrg: [{ required: true, message: '请选择组织', trigger: 'change' }],
        roles: [{ required: true, message: '请选择角色', trigger: 'change' }],
      }
    },
  },
  created() {
    this.getOrgRoleList()
    this.getData()
  },

  methods: {
    // 检索重置
    handleResetQuery() {
      this.getData()
      this.$refs['QueryInfo'].resetFields()
    },
    // 用户关键字检索
    async handleUserSearch() {
      this.showList = true
      const query = {
        keyword: this.queryInfo.userName,
        pageNo: this.page.pageNo,
        pageSize: this.page.pageSize,
      }
      const { records, total } = await findUserPageByParam(query)
      this.tableData = records
      this.page.total = total
      this.showList = false
    },
    // 切换页面
    handleCurrentChange(val) {
      this.page.pageNo = val
      this.getData()
    },
    // 删除用户数据
    delUser(userId) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          delUserList(userId).then(() => {
            this.getData()
            this.$message({
              type: 'success',
              message: '删除成功!',
            })
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },
    // 提交添加用户
    async subUserFrom() {
      await this.$refs.userForm.validate()
      this.form.userRoleVos = this.roleForm.map(item => {
        return { roleId: item }
      })
      this.form.orgUserVo.orgId = this.form.orgUserVo.id
      addUserlist(this.form).then(() => {
        this.getData()
        this.dialogVisible.addUser = false
        this.$message({
          type: 'success',
          message: '添加成功!',
        })
      })
    },
    // 提交修改
    updateUserFrom() {
      this.dialogVisible.addUser = false
      //帐号单角色
      // this.form.userRoleVos = [{ roleId: this.roleForm, userId: this.form.id }]
      // 帐号对角色
      this.form.userRoleVos = this.roleForm.map(roleId => ({ roleId, userId: this.form.id }))
      this.form.orgUserVo = this.form.orgUserVo
        ? { orgId: this.form.orgUserVo.id, userId: this.form.id }
        : { orgId: this.form.userOrgs[0].id, userId: this.form.id }
      updateUserlist(this.form).then(() => {
        this.getData()
        this.$message({
          type: 'success',
          message: '修改成功!',
        }).catch(() => {
          this.cancel()
        })
      })
    },
    // 取消按钮
    cancel() {
      this.form = {
        account: '',
        seleteOrg: '',
        dataStatusEnum: 'NORMAL',
        userOrgs: [],
        orgUserVo: null,
        userRoles: [],
      }
      this.roleForm = []
      this.dialogVisible.addUser = false
      this.$nextTick(() => {
        this.$refs['userForm'].clearValidate()
      })
    },
    // 编辑用户
    updateUser(user) {
      this.selChange = true
      this.title = '修改用户'
      this.form = Object.assign(this.form, user)
      this.form.seleteOrg = !user.userOrgs ? '' : user.userOrgs[0].name
      // this.form.orgUserVo = user.userOrgs[0] || {}
      // 帐号单角色
      // this.roleForm = user.userRoles ? user.userRoles[0].id : ''
      //帐号多角色
      this.roleForm = user.userRoles ? user.userRoles.map(({ id }) => id) : []
      this.dialogVisible.addUser = true
    },
    // 添加用户按钮
    async addUser() {
      this.title = '添加用户'
      await this.getOrgRoleList()
      this.selChange = false
      this.dialogVisible.addUser = true
    },

    // 获取数据
    async getData() {
      this.showList = true
      const { total, records } = await getUserlist(this.page)
      this.page.total = total
      this.tableData = records
      this.showList = false
    },
    // 点击组织树的节点
    handleNodeClick(obj) {
      console.log(obj)
      this.form.seleteOrg = obj.name
      this.form.orgUserVo = obj
      // this.$refs['orgSelect'].blur()
    },
    // 获取组织、角色列表
    getOrgRoleList() {
      findOrgList().then(Res => {
        this.depData = tree(Res)
      })
      findRoleList({
        pageNo: 1,
        pageSize: 100,
        total: null,
      }).then(Res => {
        this.roleData = Res.records
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.personnel-container {
  width: 100%;
  height: 100%;
  padding: vw(20px);
  background: #fff;
  box-sizing: border-box;
}

.query-container {
  display: flex;
  flex-direction: row;
}

.btn-edit {
  margin-right: vw(10px);
  color: #0084ee;

  &:hover {
    cursor: pointer;
    opacity: 0.7;
  }
}

.search-button {
  height: 100%;
  padding-top: vh(6px);
  padding-right: vw(6px);
  line-height: 100%;
  cursor: pointer;
}

.input-width {
  width: vw(350px);
}

.form-input-width {
  width: vw(250px);
}

.btn-delete {
  margin-left: vw(10px);
  color: #d12d1f;

  &:hover {
    cursor: pointer;
    opacity: 0.7;
  }
}

.custom-button + .custom-button {
  margin-left: vw(20px);
}

.selete-org-bg {
  height: vh(200px);
  padding: 0 !important;
  overflow: auto;
  background-color: #fff;
}

::-webkit-scrollbar {
  width: vw(10px);
  height: vh(1px);
}

::-webkit-scrollbar-thumb {
  background: #666;
  border-radius: 10px;
  box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.1);
  transition: background 1s;
}

::-webkit-scrollbar-track {
  background: #ededed;
  border-radius: 10px;
  box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.1);
}

::v-deep {
  .el-select .el-tag__close.el-icon-close {
    right: 0;
    color: #9a9a9a;
    background-color: transparent;
  }

  .el-tag .el-icon-close {
    font-size: vw(16px);
  }

  .el-dialog__header {
    height: vh(52px);
    padding: vh(17px) vw(23px) vh(17px);
    // background-color: #f8f8f8;
  }

  .el-dialog__title {
    font-size: vw(18px);
    font-weight: 500;
    color: #333;
  }

  .el-dialog__body {
    display: flex;
    justify-content: center;
    flex-wrap: wrap;
    padding: vh(20px);
  }

  .el-dialog__footer {
    padding: vh(10px) vw(20px) vh(20px);
    // background: #f0f4f8;
    text-align: center;
  }

  .el-form-item {
    margin-bottom: vh(22px);
  }

  .el-form-item__label {
    font-size: vw(14px);
    line-height: vh(40px);
  }

  .el-form-item__content {
    font-size: vw(14px);
    line-height: vh(40px);
  }

  .el-radio__label {
    font-size: vw(14px);
  }

  .el-tag {
    font-size: vw(12px);
  }

  .el-tree-node {
    padding: vh(4px) 0;
  }

  .el-tree-node__label {
    font-size: vw(12px);
  }
}
</style>
